package com.cloud.open.controller;

import com.cloud.common.bean.ResultInfo;
import com.cloud.open.config.AppConfig;
import com.cloud.open.constant.ErrorEnum;
import com.cloud.open.dto.LoginParamDTO;
import com.cloud.open.dto.SessionDTO;
import com.cloud.open.entity.App;
import com.cloud.open.entity.AppAuthorization;
import com.cloud.open.entity.Resource;
import com.cloud.open.service.AppAuthorizationService;
import com.cloud.open.service.AppService;
import com.cloud.open.service.ResourceService;
import com.cloud.open.support.SessionHelper;
import com.cloud.open.util.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 登录接口
 */
@RestController
public class LoginController {

    @Autowired
    private AppService appService;

    @Autowired
    private AppAuthorizationService appAuthorizationService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private SessionHelper sessionHelper;

    @Autowired
    private AppConfig appConfig;

    /**
     * 登录
     *
     * @param paramDTO
     * @return ResultInfo
     */
    @PostMapping("/open/login")
    public ResultInfo<SessionDTO> login(@Valid @RequestBody LoginParamDTO paramDTO) {
        App app = appService.getByAppId(paramDTO.getAppId());
        if (app == null) {
            return ErrorEnum.APPID_NOT_EXIST.resultInfo();
        }
        if (!app.getAppSecret().equals(paramDTO.getSecret())) {
            return ErrorEnum.APPSECRET_INCORRECT.resultInfo();
        }

        // 获取应有授权资源
        Set<String> authResources = Collections.EMPTY_SET;
        List<AppAuthorization> authorizations = appAuthorizationService.getByAppId(app.getId());
        if (!CollectionUtils.isEmpty(authorizations)) {
            List<Integer> resourceIds = authorizations.stream().map(AppAuthorization::getResourceId).collect(Collectors.toList());
            authResources = resourceService.listByIds(resourceIds).stream().map(Resource::getAccessUri).collect(Collectors.toSet());
        }

        String token = sessionHelper.createSession(app, authResources, IPUtils.buildWhitelistIp(app.getWhitelistIp()));
        SessionDTO sessionDTO = new SessionDTO();
        sessionDTO.setToken(token);
        sessionDTO.setExpiresIn(appConfig.getSessionValidSeconds());
        return ResultInfo.success().setData(sessionDTO);
    }

    /**
     * 退出
     *
     * @return ResultInfo
     */
    @PostMapping("/open/logout")
    public ResultInfo<String> logout() {
        sessionHelper.logout();
        return ResultInfo.success();
    }
}
